from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-hgos*m22o64ryot6buih4@#f5)hl$aq(z3%#bna!w*+x#=bax1"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    # "django.contrib.admin",
    # "django.contrib.auth",
    # "django.contrib.contenttypes",
    # "django.contrib.sessions",
    # "django.contrib.messages",
    "django.contrib.staticfiles",
    "hot.apps.HotConfig",
    "api.apps.ApiConfig",
    'corsheaders',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    # "django.middleware.csrf.CsrfViewMiddleware",
    # "django.contrib.auth.middleware.AuthenticationMiddleware",
    # "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "hot.utils.middle.AuthMiddleware",
    'corsheaders.middleware.CorsMiddleware',
]

# CORS_ALLOWED_ORIGINS = [
#     "*",  # 添加你的前端地址
# ]

ROOT_URLCONF = "HotManage.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / 'templates']
        ,
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                # "django.contrib.auth.context_processors.auth",
                # "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "HotManage.wsgi.application"

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": 'hot',
        'USER': 'root',
        'PASSWORD': '5201314',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
# STATIC_ROOT = BASE_DIR / 'static'
import os

# 本地用
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")  # 即静态文件存放在 BASE_DIR/static 下（和manage.py同级目录下），注意BASE_DIR指django工程的绝对路径
]
# nginx用
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = "static/"

# 静态文件的目录设置


# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "PASSWORD": "",
            # 'MAX_ENTRIES': 300,  # 最大缓存个数（默认300）
            # 'CULL_FREQUENCY': 3,  # 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）
        }
    },
    "serve": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "PASSWORD": "",
            # 'MAX_ENTRIES': 300,  # 最大缓存个数（默认300）
            # 'CULL_FREQUENCY': 3,  # 缓存到达最大个数之后，剔除缓存个数的比例，即：1/CULL_FREQUENCY（默认3）
        }
    }
}

# 设置静态文件缓存
# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
############
# SESSIONS #
############
# 存储到缓存
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
SESSION_COOKIE_AGE = 3600 * 2

PERMISSION = {
    'ADMIN': {
        "home": {"parent": None, 'text': "首页"},
        "user": {"parent": None, 'text': "用户中心"},
        'add_user': {"parent": 'user', 'text': "新建用户"},
    }
}

MENUS = {
    'ADMIN': [
        {
            "text": '首页',
            'url': '/home/',
            'icon': '&#xe68e;',
            "children": [
            ]
        },
        {
            "text": '运营管理',
            'icon': '&#xe726;',
            "children": [
                {
                    "text": '账号管理', "name": "user_list", 'url': '/user/list',
                    'children': [
                        {"text": '管理员', "name": "role_list", 'url': '/user/list'},
                    ]
                },
                # {"text": '角色管理', "name": "role_list", 'url': '/role/list'},
                # {"text": '权限管理', "name": "permission_list", 'url': '/permission/list'},
            ]
        },
        {
            "text": '菜单管理',
            'icon': '&#xe6a2;',
            "children": [
                {
                    "text": '首页配置',
                    "name": "index_list",
                    'url': '/index/list/1/',
                    'children': [
                        {"text": '首页', "name": "role_list", 'url': '/index/list/1/'},
                    ]
                },
                # {
                #     "text": '品牌介绍',
                #     "name": "user_list",
                #     'url': '',
                #     'children': [
                #         {"text": '品牌故事', "name": "role_list", 'url': '/index/list/2/'},
                #         {"text": '品牌历程', "name": "role_list", 'url': '/index/list/3/'},
                #         {"text": '品牌优势', "name": "role_list", 'url': '/index/list/4/'},
                #     ]
                # },
                {
                    "text": '菜品展示',
                    "name": "role_list",
                    'url': '',
                    'children': [
                        {"text": '招牌菜品', "name": "role_list", 'url': '/index/list/5/'},
                        {"text": '特色小吃', "name": "role_list", 'url': '/index/list/6/'},
                        {"text": '甜品饮料', "name": "role_list", 'url': '/index/list/7/'},
                    ]
                },
                {
                    "text": '门店展示',
                    "name": "permission_list",
                    'url': '',
                    'children': [
                        {"text": '门店环境', "name": "role_list", 'url': '/index/list/8/'},
                        {"text": '门店人气', "name": "role_list", 'url': '/index/list/9/'},
                    ]
                },
                # {
                #     "text": '财富共赢',
                #     "name": "permission_list",
                #     'url': '',
                #     'children': [
                #         {"text": '加盟优势', "name": "role_list", 'url': '/index/list/10/'},
                #         {"text": '合作流程', "name": "role_list", 'url': '/index/list/11/'},
                #     ]
                # },
            ]
        },
        {
            "text": '留言管理',
            'icon': '&#xe6c0;',
            "children": [
                {
                    "text": "留言", "name": 'liuyan', "url": '/liuyan/list/',
                    'children': [
                        {"text": '留言列表', "name": "liuyan", 'url': '/liuyan/list/'},
                    ]
                },
            ]
        },
        # {
        #     "text": '数据管理',
        #     "children": [
        #         {"text": "图片管理", "name": 'img_list', "url": '/img/list/'},
        #         {"text": "文案管理", "name": 'level_list', "url": '/wenan/list/'},
        #     ]
        # },

    ]
}

LOGS_DIRS = os.path.join(BASE_DIR, 'logs')
if not os.path.exists(LOGS_DIRS):
    os.makedirs(LOGS_DIRS)

# 日志
LOGGING = {
    'version': 1,  # 使用的日志模块的版本，目前官方提供的只有版本1，但是官方有可能会升级，为了避免升级出现的版本问题，所以这里固定为1
    'disable_existing_loggers': False,  # 是否禁用其他的已经存在的日志功能？肯定不能，有可能有些第三方模块在调用，所以禁用了以后，第三方模块无法捕获自身出现的异常了。
    'formatters': {  # 日志格式设置，verbose或者simple都是自定义的
        'verbose': {  # 详细格式，适合用于开发人员不在场的情况下的日志记录。
            # 格式定义：https://docs.python.org/3/library/logging.html#logrecord-attributes
            # levelname 日志等级
            # asctime   发生时间
            # module    文件名
            # process   进程ID
            # thread    线程ID
            # message   异常信息
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',  # 变量格式分隔符
        },
        'simple': {  # 简单格式，适合用于开发人员在场的情况下的终端输出
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'filters': {  # 过滤器
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {  # 日志处理流程，console或者mail_admins都是自定义的。
        'console': {
            'level': 'DEBUG',  # 设置当前日志处理流程中的日志最低等级
            'filters': ['require_debug_true'],  # 当前日志处理流程的日志过滤
            'class': 'logging.StreamHandler',  # 当前日志处理流程的核心类，StreamHandler可以帮我们把日志信息输出到终端下
            'formatter': 'simple'  # 当前日志处理流程的日志格式
        },
        # 'mail_admins': {
        #     'level': 'ERROR',                  # 设置当前日志处理流程中的日志最低等级
        #     'class': 'django.utils.log.AdminEmailHandler',  # AdminEmailHandler可以帮我们把日志信息输出到管理员邮箱中。
        #     'filters': ['special']             # 当前日志处理流程的日志过滤
        # }
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            # 日志位置,日志文件名，日志保存目录logs必须手动创建
            'filename': '%s/django.log' % LOGS_DIRS,
            # 单个日志文件的最大值，这里我们设置300M
            'maxBytes': 300 * 1024 * 1024,
            # 备份日志文件的数量，设置最大日志数量为10
            'backupCount': 10,
            # 日志格式:详细格式
            'formatter': 'verbose',
            'encoding': 'utf-8',  # 输出日志编码
        },
    },
    'loggers': {  # 日志处理的命名空间
        'django': {
            'handlers': ['cons'
                         'ole', 'file'],  # 当基于django命名空间写入日志时，调用那几个日志处理流程
            'propagate': True,  # 是否在django命名空间对应的日志处理流程结束以后，冒泡通知其他的日志功能。True表示允许
        },
    }
}

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'

# 解决内嵌iframe
X_FRAME_OPTIONS = 'SAMEORIGIN'

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

# CORS_ORIGIN_WHITELIST = (
#
#     '*'
#
# )
# 跨域
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

# 跨域
SECURE_CROSS_ORIGIN_OPENER_POLICY = 'None'
# cos图片处理
# IP_COS = 'https://img-1317812744.cos.ap-nanjing.myqcloud.com/'
IP_COS = 'http://127.0.0.1:8000/media/'
try:
    from .local_settings import *
except:
    pass
